package uk.ac.cam.djjb2.mygame;

import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

public class IdManager<T> {
	private Map<Integer, T> idMap = new ConcurrentHashMap<Integer, T>();
	private int nextId = 1;
	
	public IdManager() {
	}
	
	public synchronized int put(T obj) {
		idMap.put(nextId, obj);
		
		return nextId++;
	}
	public synchronized void put(int id, T obj) {
		idMap.put(id, obj);
		if (id >= nextId)
			nextId = id + 1;
	}
	public T get(int id) {
		return idMap.get(id);
	}
	public <U extends T> U get(int id, Class<U> type) {
		return type.cast(get(id));
	}
	public synchronized void clear() {
		nextId = 1;
		idMap.clear();
	}
	public T remove(int id) {
		return idMap.remove(id);
	}
	public <U extends T> U remove(int id, Class<U> type) {
		return type.cast(remove(id));
	}
	public Set<Integer> getIds() {
		return Collections.unmodifiableSet(idMap.keySet());
	}
	public Collection<T> getObjects() {
		return Collections.unmodifiableCollection(idMap.values());
	}
}
